package com.hst.capacity.domain.service.impl;

import cn.smartravel.traffic.alitrip.AlitripCarOpen;
import com.alibaba.fastjson2.JSON;
import com.hst.capacity.application.biz.SmsBiz;
import com.hst.capacity.application.biz.VehicleBiz;
import com.hst.capacity.domain.common.constants.AliTripTransferConstants;
import com.hst.capacity.domain.common.constants.MessageTemplate;
import com.hst.capacity.domain.exception.BusinessException;
import com.hst.capacity.domain.model.entity.order.pool.OrderPoolEntity;
import com.hst.capacity.domain.model.response.driver.DriverInfoVO;
import com.hst.capacity.domain.service.AliTripService;
import com.hst.capacity.domain.service.DriverService;
import com.hst.capacity.domain.service.OrderPoolService;
import com.hst.capacity.infra.persistence.jpa.order.pool.OrderPoolRepository;
import com.hst.capacity.infra.util.DateUtil;
import com.hst.capacity.infra.util.StringUtil;
import com.taobao.api.request.AlitripCarOrderConfirmRequest;
import com.taobao.api.response.AlitripCarOrderConfirmResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Locale;

@Slf4j
@Service
public class AliTripServiceImpl implements AliTripService {

    @Autowired
    DriverService driverService;

    @Autowired
    AlitripCarOpen alitripCarOpen;

    @Autowired
    OrderPoolService orderPoolService;

    @Autowired
    OrderPoolRepository orderPoolRepository;

    @Autowired
    SmsBiz smsBiz;

    @Autowired
    VehicleBiz vehicleBiz;

    @Override
    public void virtualAcceptOrder(String idOrder) {

        OrderPoolEntity order = orderPoolRepository.findByIdOrder(idOrder);
        this.virtualAcceptAction(order);

    }

    @Override
    public void virtualAcceptAction(OrderPoolEntity order) {

        log.info("虚拟接单 virtualAcceptAction: {}", JSON.toJSONString(order));
        String idDriver = AliTripTransferConstants.AliTrip_VirtualDriver.get(order.getIdFranchisee());
        //司机和车辆信息
        DriverInfoVO driverInfoVO = driverService.driverInfo(idDriver);
        if (driverInfoVO == null)
            throw new BusinessException(5001, "未找到对应的虚拟司机的信息");

        long confirmType = 0L;
        if (StringUtil.isNotBlank(order.getIdDriver()))
            confirmType = 1L;

        /**
         * 改派司机接口：
         */
        AlitripCarOrderConfirmRequest.OrderConfirm orderConfirm = new AlitripCarOrderConfirmRequest.OrderConfirm();
        //JSON.toJSONString(orderConfirm);
        orderConfirm.setConfirmTime(DateUtil.getNowLocalDate());
        //0应答 1改派
        orderConfirm.setConfirmType(confirmType);
        orderConfirm.setOrderId(order.getExternalOrderId());
        orderConfirm.setProviderId(AliTripTransferConstants.ProviderIdWithMemberID.get(order.getIdMember()));
        orderConfirm.setThirdOrderId(order.getIdOrder());
        //0:接送机 1：实时打车 2：租车(不传值默认为0)
        orderConfirm.setUseType(0L);
        //车辆描述,车辆颜色,候车地点等：红色,T3出口
//                String carDesc = String.format("%s,%s",param.getVehicleColor(),"黄花机场T1");
//                orderConfirm.setDriverCarDesc(carDesc);
        //司机车型名称:奔驰C200
        String carName = String.format("%s%s", driverInfoVO.getBrand(), driverInfoVO.getModel());
        orderConfirm.setDriverCarName(driverInfoVO.getBrand());
        //司机车牌号:浙A111111
        orderConfirm.setDriverCarNo(driverInfoVO.getPlateNumber());
        orderConfirm.setDriverName(driverInfoVO.getRealName());
        orderConfirm.setDriverCarColor(driverInfoVO.getColor());
        orderConfirm.setCarBrand(driverInfoVO.getBrand());
        orderConfirm.setCarModel(driverInfoVO.getModel());
        //司机联系方式。格式：加号+国家区号+空格+当地电话号码 +86 13266365287
        String tel = driverInfoVO.getDriverMobile();
        if (!tel.contains("+86"))
            tel = String.format("+86 %s", tel);
        orderConfirm.setDriverTel(tel);
//                //车龄
//                orderConfirm.setCarAge();
//                //司机性别
//                orderConfirm.setDeriverGender();
        //司机图片，公网可访问链接
//                orderConfirm.setDriverPic();
//                orderConfirm.setCarPic();

//                log.info("orderConfirm:" + JSON.toJSONString(orderConfirm));

        String tenant = AliTripTransferConstants.MemberIDFindMerchant.get(order.getIdMember());
        AlitripCarOrderConfirmResponse res = alitripCarOpen.orderConfirm(orderConfirm, tenant);

        if (res == null || res.getMessage() == null
                || !(res.getMessage().equals("成功") || res.getMessage().toLowerCase(Locale.ROOT).equals("ok"))) {
            log.info("res:" + res.getMessage() + "data:"  + res.getData());
            throw new BusinessException(5002, "飞猪接口回调失败，请重新执行");
        }

        String dpInfo = tel + "/" + driverInfoVO.getRealName();
        orderPoolService.virtualAcceptOrder(order, idDriver, dpInfo);

        String dispatcher_mobile = AliTripTransferConstants.AliTrip_Dispatcher.get(order.getIdFranchisee());

        if (StringUtil.isNotBlank(dispatcher_mobile)) {
            //给调度员发短信
            smsBiz.sendNewOrderSms(dispatcher_mobile, order.getAppointmentTime(), order.getIdVehicleType(), order.getIdMember());
        }
    }

}
